import Vue from 'vue'
import Router from 'vue-router'
import Detail from '@/views/Detail'
import store from '@/store/index.js'
// 引入二级路由
import MyOrder from '@/views/Center/myOrder'
import GroupOrder from '@/views/Center/groupOrder'
Vue.use(Router)
let originPush = Router.prototype.push;
let originReplace = Router.prototype.replace;
const originalPush = Router.prototype.push
Router.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
Router.prototype.push = function(location, resolve, reject) {
  //第一个形参：路由跳转的配置对象（query|params）
  //第二个参数：undefined|箭头函数（成功的回调）
  //第三个参数:undefined|箭头函数（失败的回调）
  if (resolve && reject) {
    //push方法传递第二个参数|第三个参数（箭头函数）
    //originPush：利用call修改上下文，变为(路由组件.$router)这个对象，第二参数：配置对象、第三、第四个参数：成功和失败回调函数
    originPush.call(this, location, resolve, reject);
  } else {
    //push方法没有产地第二个参数|第三个参数
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};
//重写VueRouter.prototype身上的replace方法了
Router.prototype.replace = function(location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject);
  } else {
    originReplace.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};
// 路由懒加载
let router = new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: resolve => require(['@/views/Home'], resolve),
      meta: { show: true }
    },
    {
      path: '/center',
      name: 'Center',
      component: resolve => require(['@/views/Center'], resolve),
      meta: { show: true },
      // 二级路由组件
      children:[
        {
          path:'myOrder',
          component:MyOrder
        },
        {
          path:'groupOrder',
          component:GroupOrder
        },
        {
          path:'/center',
          redirect:'/center/myOrder'
        }
      ]
    },
    {
      path: '/paysuccess',
      name: 'PaySuccess',
      component: resolve => require(['@/views/PaySuccess'], resolve),
      meta: { show: true }
    },
    {
      path: '/pay',
      name: 'Pay',
      component: resolve => require(['@/views/Pay'], resolve),
      meta: { show: true },
      beforeEnter(to,from,next){
        //必须从交易页面跳到支付页面
        if(from.path=='/trade'){
          next()
        }else{
          next(false)
        }
      }
    },
    {
      path: '/trade',
      name: 'Trade',
      component: resolve => require(['@/views/Trade'], resolve),
      meta: { show: true },
      beforeEnter(to,from,next){
        //必须从购物页面跳到交易页面
        if(from.path=='/shopcart'){
          next()
        }else{
          next(false)
        }
      }
    },
    {
      path: '/addcartsuccess',
      name: 'Addcartsuccess',
      component: resolve => require(['@/views/AddCartSuccess'], resolve),
      meta: { show: true }
    },
    {
      path: '/shopcart',
      name: 'ShopCart',
      component: resolve => require(['@/views/ShopCart'], resolve),
      meta: { show: true }
    },
    {
      path: '/detail/:skuId',
      name: 'Detail',
      component: resolve => require(['@/views/Detail'], resolve),
      meta: { show: true }
    },
    {
      path: '/search/:keyword?',
      name: 'search',
      component: resolve => require(['@/views/Search'], resolve),
      meta: { show: true },
      // 路由组件可以传递props数据
      props: ($route) => {
        return { keyword: $route.params.keyword, k: $route.query.k }
      }
    },
    {
      path: '/login',
      name: 'login',
      component: resolve => require(['@/views/Login'], resolve),
      meta: { show: false }
    },
    {
      path: '/register',
      name: 'register',
      component: resolve => require(['@/views/Register'], resolve),
      meta: { show: false }
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (about.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
    }
  ],
  scrollBehavior (to, from, savedPosition) {
    return { y: 0 }
  }
})

//全局守卫：前置守卫（在路由跳转之前进行判断）
router.beforeEach(async (to, from, next) => {
  //to:获取到要跳转到的路由信息
  //from：获取到从哪个路由跳转过来来的信息
  //next: next() 放行  next(path) 放行
  //方便测试 统一放行
  //  next();
  //获取仓库中的token-----可以确定用户是登录了
  let token  = store.state.user.token;
  let name = store.state.user.userInfo.name;
  //用户登录了
  if(token){
    //已经登录而且还想去登录------不行
    if(to.path=="/login"||to.path=='/register'){
      next('/');
    }else{
      //已经登陆了,访问的是非登录与注册
      //登录了且拥有用户信息放行
      if(name){
        next();
      }else{
        //登陆了且没有用户信息
        //在路由跳转之前获取用户信息且放行
        try {
          await store.dispatch('getUserInfo');
          next();
        } catch (error) {
          //token失效但是还存在需要清除,重新登录
          await store.dispatch('userLogOut');
          next('/login')
        }
      }
    }
  }else{
    // 未登录不能去支付交易页面，个人中心
    let toPath = to.path
    if(toPath.indexOf('/trade')!=-1||toPath.indexOf('/pay')!=-1||toPath.indexOf('/paysuccess')!=-1||toPath.indexOf('/center')!=-1){
     next('/login?redirect='+toPath)
    }else{
      next()
    }
  }
});
export default router
